package com.dyzx.hbb.modules.fcxs.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.alibaba.fastjson2.JSONObject;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.utils.Utils;
import com.dyzx.hbb.modules.fcxs.entity.FcxsClue;
import com.dyzx.hbb.modules.fcxs.service.FcxsClueService;
import com.dyzx.hbb.modules.fcxs.vo.FcxsClueVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * 外部接口控制器
 * 
 * 功能说明：提供与外部系统集成的API接口，处理外部系统发起的数据交互请求
 * 主要职责：
 * - 提供线索数据的外部新增接口
 * - 实现数据加密解密处理
 * - 验证外部请求的合法性
 * - 处理外部系统与内部系统的数据交互
 * 
 * @author 开发团队
 * @version 1.0.0
 * @since 2023-05-30
 */
@RestController
@Tag(name = "接口管理", description = "接口管理相关接口")
@RequestMapping("/fcxs/interface")
public class FcxsInterfaceController {
    @Autowired
    private FcxsClueService fcxsClueService;
    /**
     * JWT密钥 (Base64编码)
     */
    @Value("${jwt.secret:}")
    private String secret;

    // 线索新增:/fcxs/interface/clue
    @Operation(summary = "线索新增")
    @PostMapping("/clue")
    public Result<Boolean> clue(@RequestBody @Valid FcxsClueVO entity,@RequestBody String token) {
        // 随机生成密钥
        SymmetricCrypto sm4 = SmUtil.sm4();
        String s = sm4.decryptStr(token);
        JSONObject jsonObject = JSONObject.parseObject(s);


        FcxsClue data = addClueValid(entity);
        boolean organFlag = jsonObject.containsKey("organ_id");
        if (!organFlag) {

            return Result.error("请传入organ_id");
        } else {
            Long organId = jsonObject.getLong("organ_id");
            data.setOrganId(organId);
        }

        boolean save = fcxsClueService.save(data);
        return save? Result.ok(save) : Result.error("新增失败");
    }


    protected FcxsClue addClueValid(FcxsClueVO entity) {
        FcxsClue data = new FcxsClue();
        BeanUtil.copyProperties(entity, data);
        String s = Utils.generateYyMMOrderNumber("XS");
        data.setClueNo(s);
        return data;
    }
}
